package com.sunnyweather.android.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object SunnyWeatherNetwork {
    //使用ServiceCreator创建weatherService接口的动态代理对象
    private val weatherService = ServiceCreator2.create(WeatherService::class.java)
    //定义searchPlaces()函数，调用接口中定义的getDailyWeather()方法，发起搜索选中的城市的未来七天天气预报的请求
    suspend fun getDailyWeather(locationId: String) = weatherService.getDailyWeather(locationId).await()
    //定义searchPlaces()函数，调用接口中定义的getRealtimeWeather()方法，发起搜索选中城市现在的天气情况请求
    suspend fun getRealtimeWeather(locationId: String) = weatherService.getRealtimeWeather(locationId).await()
    //使用ServiceCreator创建PlaceService接口的动态代理对象
    private val placeService = ServiceCreator.create(PlaceService::class.java)
    //定义searchPlaces()函数，调用接口中定义的searchPlaces()方法，发起搜索城市数据请求
    suspend fun searchPlaces(location: String) = placeService.searchPlaces(location).await()

    //统一的网络数据源访问入口，对所有网络请求API进行封装
    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) {
                        continuation.resume(body)
                    }
                    else continuation.resumeWithException(RuntimeException("response body is null"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }

}